package com.cicadamob.contact.api.http.handler;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONException;

import com.cicadamob.contact.api.http.dao.PersonCenterRequest;
import com.gmccgz.im.sdk.http.bean.MediaCardDetail;
import com.gmccgz.im.sdk.http.bean.UploadFile;
import com.gmccgz.im.sdk.http.bean.UserCard;
import com.gmccgz.im.sdk.http.handler.MediaDownload;
import com.gmccgz.im.sdk.http.handler.MediaUploadStorage;
import com.gmccgz.im.sdk.http.handler.TransferCallBack;

public class PersonCenterHandle {

	/**
	 * 请求的数据
	 */
	public static String requestStr;

	public static String getRequestStr() {
		return requestStr;
	}

	public static void setRequestStr(String requestStr) {
		PersonCenterHandle.requestStr = requestStr;
	}

	/** 编辑个人名片 */
	public static String editPersonalCard(String ipPort, String userId,
			String nickname, String mood_sign, String homepage, String fromid,
			String imsi, String imei, String token, String messageId,
			String location) {
		String str = "http://%1$s/portal/api/editPersonalCard";
		String url = String.format(str, ipPort);

		String request = PersonCenterRequest.getEditPersonalCardRequest(fromid,
				imsi, imei, token, messageId, userId, nickname, mood_sign,
				homepage, location);
		String reponse = sendPostRequest(url, request);
		setRequestStr(url + "\n" + request);
		return reponse;
	}

	/** 同步个人名片old */
	// public static String synchroPersonalCard(String ipPort, String fromid,
	// String imsi, String imei, String token, String messageId,
	// String mobile) {
	// String str = "http://%1$s/portal/api/synchroPersonalCard";
	// String url = String.format(str, ipPort);
	// String request = PersonCenterRequest.getSynchroPersonalCardRequest(
	// fromid, imsi, imei, token, messageId, mobile);
	// String reponse = sendPostRequest(url, request);
	// setRequestStr(url + "\n" + request);
	// return reponse;
	// }
	/**
	 * 同步个人名片 new
	 * 
	 * @throws JSONException
	 */
	public static String synchroPersonalCard(String ipPort, String fromid,
			String imsi, String imei, String token, String messageId,
			ArrayList<UserCard> listCard) throws JSONException {
		String str = "http://%1$s/portal/api/synchroPersonalCard";
		String url = String.format(str, ipPort);
		String request = PersonCenterRequest.getSynchroPersonalCardRequestNew(
				fromid, imsi, imei, token, messageId, listCard);
		String reponse = sendPostRequest(url, request);
		setRequestStr(url + "\n" + request);
		return reponse;
	}

	/**
	 * 5.1 上传通讯关系
	 * 
	 * @throws JSONException
	 */
	public static String uploadRelation(String ipPort, String fromid,
			String imsi, String imei, String token, String messageId,
			String id, int type, ArrayList<UserCard> listCard) {
		String str = "http://%1$s/portal/api/uploadRelation";
		String url = String.format(str, ipPort);
		String request = PersonCenterRequest.getUploadRelation(fromid, imsi,
				imei, token, messageId, id, type, listCard);
		String reponse = sendPostRequest(url, request);
		setRequestStr(url + "\n" + request);
		return reponse;
	}

	/**
	 * 5.2 增加通讯号码
	 * 
	 * @throws JSONException
	 */
	public static String addRelationUser(String ipPort, String fromid,
			String imsi, String imei, String token, String messageId,
			String id, int type, ArrayList<UserCard> listCard) {
		String str = "http://%1$s/portal/api/addRelationUser";
		String url = String.format(str, ipPort);
		String request = PersonCenterRequest.getUploadRelation(fromid, imsi,
				imei, token, messageId, id, type, listCard);
		String reponse = sendPostRequest(url, request);
		setRequestStr(url + "\n" + request);
		return reponse;
	}

	/**
	 * 5.3 增加通讯号码
	 * 
	 * @throws JSONException
	 */
	public static String modifyRelationUser(String ipPort, String fromid,
			String imsi, String imei, String token, String messageId,
			String id, int type, ArrayList<UserCard> listCard) {
		String str = "http://%1$s/portal/api/modifyRelationUser";
		String url = String.format(str, ipPort);
		String request = PersonCenterRequest.modifyRelationUser(fromid, imsi,
				imei, token, messageId, id, type, listCard);
		String reponse = sendPostRequest(url, request);
		setRequestStr(url + "\n" + request);
		return reponse;
	}

	/**
	 * 5.4 删除通讯号码
	 * 
	 * @throws JSONException
	 */
	public static String deleteRelationUser(String ipPort, String fromid,
			String imsi, String imei, String token, String messageId,
			String id, int type, String user) {
		String str = "http://%1$s/portal/api/deleteRelationUser";
		String url = String.format(str, ipPort);
		String request = PersonCenterRequest.deleteRelationUser(fromid, imsi,
				imei, token, messageId, id, type, user);
		String reponse = sendPostRequest(url, request);
		setRequestStr(url + "\n" + request);
		return reponse;
	}

	/**
	 * 1.15 上传留言接口
	 * http://ip:port/portal/api/uploadMessage?signature=fromid:FROMID
	 * ,imsi:IMSI,
	 * imei:IMEI,token:TOKEN&toUser=type:1,id:15918611748&timestamp=TIMESTAMP
	 */
	public static String uploadMessage(String ipPort, String fromid,
			String imsi, String imei, String token, String timestamp,
			String id, int type) {

		String uploadMessage = "http://" + ipPort
				+ "/portal/api/uploadMessage?signature=fromid:" + fromid
				+ ",imsi:" + imsi + ",imei:" + imei + ",token:" + token
				+ "&toUser=type:" + type + ",id:" + id + "&timestamp="
				+ timestamp;

		return uploadMessage;

	}

	/**
	 * 1.16 下载留言接口
	 * http://ip:port/portal/api/downloadMessage?signature=fromid:FROMID
	 * ,imsi:IMSI,imei:IMEI, token:TOKEN&timestamp=TIMESTAMP&mediaId=MEDIAID
	 */

	public static String downloadMessage(String ipPort, String fromid,
			String imsi, String imei, String token, String timestamp,
			String mediaId) {
		String downloadMessage = "http://%1$s/portal/api/downloadMessage?signature=fromid:%2$s,"
				+ "imsi:%3$s,imei:%4$s,token:%5$s&timestamp=%6$s&mediaId=%7$s";

		return String.format(downloadMessage, ipPort, fromid, imsi, imei,
				token, timestamp, mediaId);

	}

	/**
	 * 1.17 删除留言
	 */
	public static String deleteMessage(String ipPort, String fromid,
			String imsi, String imei, String token, String messageId,
			String mediaId) {
		String str = "http://%1$s/portal/api/deleteMessage";
		String url = String.format(str, ipPort);

		String request = PersonCenterRequest.getDeleteMediaRequest(fromid,
				imsi, imei, token, messageId, mediaId);

		String reponse = sendPostRequest(url, request);
		setRequestStr(url + "\n" + request);
		return reponse;

	}

	/**
	 * 获取头像媒体ID
	 */
	public static String getHeadMediaId(String ipPort, String fromid,
			String imsi, String imei, String token, String messageId,
			String id, int type) {
		String str = "http://%1$s/portal/api/getHeadMediaId";
		String url = String.format(str, ipPort);
		String request = PersonCenterRequest.getHeadMediaId(fromid, imsi, imei,
				token, messageId, id, type);
		String reponse = sendPostRequest(url, request);
		setRequestStr(url + "\n" + request);
		return reponse;
	}

	/** 编辑企业名片 */
	public static String editCompanyCard(String ipPort, String companyCode,
			String companyId, String introduction, String address,
			String phone, String homepage, String fromid, String imsi,
			String imei, String token, String messageId) {
		String str = "http://%1$s/portal/api/editCompanyCard";
		String url = String.format(str, ipPort);

		String request = PersonCenterRequest.getEditCompanyCardRequest(fromid,
				imsi, imei, token, messageId, companyCode, companyId,
				introduction, address, phone, homepage);
		String reponse = sendPostRequest(url, request);
		setRequestStr(url + "\n" + request);
		return reponse;
	}

	/** 同步企业名片 */
	public static String synchroCompanyCard(String ipPort, String companyId,
			String fromid, String imsi, String imei, String token,
			String messageId) {

		String str = "http://%1$s/portal/api/synchroCompanyCard";
		String url = String.format(str, ipPort);

		String request = PersonCenterRequest.getSynchroCompanyCardRequest(
				fromid, imsi, imei, token, messageId, companyId);
		String reponse = sendPostRequest(url, request);
		setRequestStr(url + "\n" + request);
		return reponse;
	}

	/** 查询来电号码名片 */
	public static String queryInCallCard(String ipPort, String phone,
			String fromid, String imsi, String imei, String token,
			String messageId) {
		String str = "http://%1$s/portal/api/queryInCallCard";
		String url = String.format(str, ipPort);

		String request = PersonCenterRequest.getQueryInCallCardRequest(fromid,
				imsi, imei, token, messageId, phone);
		String reponse = sendPostRequest(url, request);
		setRequestStr(url + "\n" + request);
		return reponse;
	}

	/** 删除图片 */
	public static String deleteMedia(String ipPort, String mediaId,
			String fromid, String imsi, String imei, String token,
			String messageId) {
		String str = "http://%1$s/portal/api/deleteMedia";
		String url = String.format(str, ipPort);
		String request = PersonCenterRequest.getDeleteMediaRequest(fromid,
				imsi, imei, token, messageId, mediaId);
		String reponse = sendPostRequest(url, request);
		System.out.println("deleteMedia.request" + request.toString());
		setRequestStr(url + "\n" + request);
		return reponse;
	}

	/** 设置封面 */
	public static String setCover(String ipPort, String mediaId, String fromid,
			String imsi, String imei, String token, String messageId) {
		String str = "http://%1$s/portal/api/setCover";
		String url = String.format(str, ipPort);

		String request = PersonCenterRequest.getSetCoverRequest(fromid, imsi,
				imei, token, messageId, mediaId);
		String reponse = sendPostRequest(url, request);
		setRequestStr(url + "\n" + request);
		return reponse;
	}

	/** 上传名片 */
	public static String uploadCardIp(String ipPort, String fromid,
			String toid, String usertype, String token, String imsi,
			String imei, String mediadetail, File file, int fileType,
			TransferCallBack callBack) {
		String str = "http://%1$s/portal/api/uploadCard";
		String url = String.format(str, ipPort);

		MediaUploadStorage mu = new MediaUploadStorage(url, file, fileType,
				fromid, toid, usertype, token, imsi, imei, mediadetail);
		mu.setCallBack(callBack);
		setRequestStr(mu.getUploadUrl());
		String result = mu.uploadMedia();
		return result;
	}

	/**
	 * 1.18 调整封面名片顺序
	 * 
	 * @return
	 */
	public static String updateMediaCardDetail(String ipPort, String fromid,
			String imsi, String imei, String token, String messageId,
			ArrayList<MediaCardDetail> listDetail) {
		String str = "http://%1$s/portal/api/updateMediaCardDetail";
		String url = String.format(str, ipPort);

		String request = PersonCenterRequest.updateMediaCardDetail(fromid,
				imsi, imei, token, messageId, listDetail);
		String reponse = sendPostRequest(url, request);
		setRequestStr(url + "\n" + request);
		return reponse;
	}

	/** 上传 */
	public static String uploadIp(String ipPort, String fromid, String toid,
			String usertype, String token, String imsi, String imei,
			String mediadetail, File file, int fileType,
			TransferCallBack callBack) {
		String str = "http://%1$s/portal/api/upload";
		String url = String.format(str, ipPort);

		MediaUploadStorage mu = new MediaUploadStorage(url, file, fileType,
				fromid, toid, usertype, token, imsi, imei, mediadetail);
		mu.setCallBack(callBack);
		setRequestStr(mu.getUploadUrl());
		String result = mu.uploadMedia();
		return result;
	}

	/** 下载名片 */
	public static String downloadCardIp(String ipPort, String media_id,
			String fromid, String token, String fileSavePath, String imsi,
			String imei, int type, String officenumber,
			TransferCallBack callBack) {
		String str = "http://%1$s/portal/api/downloadCard";
		String url = String.format(str, ipPort);

		MediaDownload md = new MediaDownload(url, media_id, fromid, token,
				fileSavePath, imsi, imei, UploadFile.TYPE_IMAGE, officenumber);
		md.setCallBack(callBack);
		setRequestStr(md.getDownloadUrl());

		String result = md.downloadMedia();
		return result;
	}

	/** 下载 */
	public static String downloadIp(String ipPort, String media_id,
			String fromid, String token, String fileSavePath, String imsi,
			String imei, int type, String officenumber,
			TransferCallBack callBack) {
		String str = "http://%1$s/portal/api/download";
		String url = String.format(str, ipPort);

		MediaDownload md = new MediaDownload(url, media_id, fromid, token,
				fileSavePath, imsi, imei, UploadFile.TYPE_IMAGE, officenumber);
		md.setCallBack(callBack);
		setRequestStr(md.getDownloadUrl());

		String result = md.downloadMedia();
		return result;
	}

	public static String sendPostRequest(String targetUrl, String request) {
		// System.out.println(targetUrl);
		// System.out.println(request);
		long startTime = System.currentTimeMillis();
		InputStream in = null;
		DataOutputStream ds = null;
		String log_response = null;
		try {
			URL url = new URL(targetUrl);// MalformedURLException
			HttpURLConnection con = (HttpURLConnection) url.openConnection();// IOException
			con.setRequestMethod("POST");// ProtocolException
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setConnectTimeout(5 * 1000);
			con.setReadTimeout(5 * 1000);
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			// con.setRequestProperty("Accept-Encoding", "gzip");

			ds = new DataOutputStream(con.getOutputStream()); // IOException
			if (null != request && !"".equals(request)) {
				ds.write(request.getBytes());
			}

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					con.getInputStream(), "UTF-8"));
			StringBuilder sb = new StringBuilder();
			String lineStr = null;
			while (null != (lineStr = reader.readLine())) {// IOException
				sb.append(lineStr);
			}
			log_response = sb.toString();
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			log_response = e.toString();
		} finally {
			// HttpLogUtil.writeLog(targetUrl, request, log_response, startTime,
			// System.currentTimeMillis());
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != ds) {
				try {
					ds.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

}
